package cn.zhfeat.utils;

import org.apache.commons.beanutils.BeanComparator;
import org.apache.commons.collections.ComparatorUtils;
import org.apache.commons.collections.comparators.ComparableComparator;
import org.apache.commons.collections.map.MultiValueMap;
import org.apache.commons.lang.StringUtils;
import org.apache.commons.lang.exception.ExceptionUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.io.*;
import java.util.*;


/**
 * 集合操作类
 * 
 * @author zhanghao
 * 
 */
@SuppressWarnings("all")
public class ListUtil {
	
	protected static Logger logger = LoggerFactory.getLogger(ListUtil.class);
	
	/**
	 * 删去list中map中的某一列
	 * @param list
	 * @param toBeRemoved
	 */
	public static  void cleanListByMapKey(List<Map> list, String toBeRemoved) {
//	    List<Map> tmpList=new ArrayList();
	    if(null!=list && list.size()>0){
	    	for(Map  m: list){
	    		if(m.containsKey(toBeRemoved))
	    			m.remove(toBeRemoved);
	    	}
	    }
	}

	/**
	 * 将字符数组转换为字符串
	 * 
	 * @param arr
	 * @return
	 */
	public static String list2String(List list) {
		StringBuffer sb = new StringBuffer();
		if (list.size() <= 0) {
			sb.append("('')");
			return sb.toString();
		}
		if (null != list && list.size() > 0) {
			sb.append("(");
			for (int i = 0; i < list.size(); i++) {
				sb.append(list.get(i)).append(",");
			}
			sb.delete(sb.length() - 1, sb.length());
			sb.append(")");
		}
		return sb.toString();
	}
	/**
	 * 将字符数组转换为字符串
	 * 
	 * @param arr
	 * @return
	 */
	public static String list2String2(List list) {
		StringBuffer sb = new StringBuffer();
		if (list.size() <= 0) {
			sb.append("('')");
			return sb.toString();
		}
		if (null != list && list.size() > 0) {
			sb.append("(");
			for (int i = 0; i < list.size(); i++) {
				sb.append("'").append(list.get(i)).append("'").append(",");
			}
			sb.delete(sb.length() - 1, sb.length());
			sb.append(")");
		}
		return sb.toString();
	}
	
		public static String listforString(List list) {
			StringBuffer sb = new StringBuffer();
			if (list.size() <= 0) {
				sb.append("('')");
				return sb.toString();
			}
			if (null != list && list.size() > 0) {
				sb.append("(");
				for (int i = 0; i < list.size(); i++) {
					sb.append("'").append(list.get(i)).append("'").append(",");
				}
				sb.delete(sb.length() - 1, sb.length());
				sb.append(")");
			}
			return sb.toString();
		}

	/**
	 * 将字符数组转换为字符串
	 * 
	 * @param arr
	 * @return
	 */
	public static String arr2String(Object[] arr) {
		StringBuffer sb = new StringBuffer();
		if (arr.length <= 0) {
			sb.append("('')");
			return sb.toString();
		}
		if (null != arr && arr.length > 0) {
			sb.append("('");
			for (int i = 0; i < arr.length; i++) {
				sb.append(arr[i]).append(",");
			}
			sb.delete(sb.length() - 1, sb.length());
			sb.append("')");
		}
		return sb.toString();
	}

	/**
	 * 如果没有，则补空 0
	 * 
	 * @param full
	 * @param select
	 * @param map
	 * @param key
	 * @return
	 */
	public static List additionalProperty(List full, List select,Map map , String key) {
		// 返回集合
		List returnList = new ArrayList();
		// 比较集合
		List compList = new ArrayList();
		// 结构
		Map stust = new HashMap();
		if (null != full && full.size() > 0 ) {
				if(null!=select && select.size()>0){
					// 初始化结构和数组
					extractDiff(select, map, key, compList);
					for (int i = 0; i < full.size(); i++) {
						String keys = (String) full.get(i);
						if (!compList.contains(keys)) {
							//初始化某一条值
							Map result = intiOneStructure(full, map, key, i);
							returnList.add(result);
						}
					}
				}else{
					for (int i = 0; i < full.size(); i++) {
						String keys = (String) full.get(i);
						Map result = intiOneStructure(full, map, key, i);
						returnList.add(result);
					}
				}
		}
	
		return returnList;
	}

	/**
	 * 初始化某一条的结构
	 * @param full
	 * @param map
	 * @param key
	 * @param i
	 * @return
	 */
	private static Map intiOneStructure(List full, Map map, String key, int i) {
		Map rest = new HashMap();
		Iterator<Map.Entry<String, String>> it = map
				.entrySet().iterator();
		while (it.hasNext()) {
			Map.Entry<String, String> entry = it.next();
			if (entry.getKey().equals(key)) {
				rest.put(entry.getKey(), full.get(i));
			} else {
				rest.put(entry.getKey(), 0);
			}
		}
		return rest;
	}

	/**
	 * 抽取差异的
	 * @param select  集合
	 * @param map 结合中项结构
	 * @param key 关键字
	 * @param compList 初始化zhi的结构
	 */
	private static void extractDiff(List select, Map map, String key,
			List compList) {
		for (int i = 0; i < select.size(); i++) {
			Map maps = (Map)select.get(i);
			Iterator<Map.Entry<String, String>> it = maps
					.entrySet().iterator();
			while (it.hasNext()) {
				Map.Entry<String, String> entry = it.next();
				if (entry.getKey().equals(key)) {
					compList.add(entry.getValue());
				}
			}
		}
	}
	
	/**
	 * 删去list中map中的某一列
	 * @param list
	 * @param str
	 */
	public static void removeListByKeys(List<Map> list, String str) {
		if(null != list && !list.isEmpty() && StringUtils.isNotBlank(str) && str.indexOf(",") > 0){
			String[] arr = str.split(",");
			for(int i = 0;i<arr.length;i++){
				for(Map  m: list){
		    		if(m.containsKey(arr[i]))
		    			m.remove(arr[i]);
		    	}
			}
		}else{
			throw new IllegalArgumentException("非法传入的参数!");
		}
	}
	/**
	 * 删去list中map中的某一列
	 * @param list
	 * @param str
	 */
	public static void removeMultMapListByKeys(List<MultiValueMap> list, String str) {
		if(null != list && !list.isEmpty() && StringUtils.isNotBlank(str) && str.indexOf(",") > 0){
			String[] arr = str.split(",");
			for(int i = 0;i<arr.length;i++){
				for(int ii = 0; ii < list.size();ii++){
					Map map = list.get(ii);
					try {
						if(map.containsKey(arr[i])){
							map.remove(arr[i]);
			    		}
					} catch (Exception e) {
						logger.debug(ExceptionUtils.getFullStackTrace(e));
					}
				}
//				for(Map  m: list){
//		    		if(m.containsKey(arr[i]))
//		    			m.remove(arr[i]);
//		    	}
			}
		}else{
			throw new IllegalArgumentException("非法传入的参数!");
		}
	}
	/**
	 * 排序集合
	 * 
	 * @param list
	 *            要排序的list
	 * @param propertyName
	 *            属性名
	 * @param isDesc
	 *            是否降序排序 true：降序
 	 * @return
	 */
	public static void sortList(List list, String propertyName, boolean isDesc) {
		//创建一个排序规则  
		Comparator mycmp = ComparableComparator.getInstance();
		mycmp = ComparatorUtils.nullLowComparator(mycmp); // 允许null
		if (isDesc) {
			mycmp = ComparatorUtils.reversedComparator(mycmp); // 反序
		}
		Comparator cmp = new BeanComparator(propertyName, mycmp);
		Collections.sort(list, cmp);
	}
		/**
		 * 深度复制两个list数据
		 * @param src
		 * @return
		 */
		public static <T> List<T> deepCopyList(List<T> src)
		{
		    List<T> dest = null;
				try {
					ByteArrayOutputStream byteOut = new ByteArrayOutputStream();
			        ObjectOutputStream out = new ObjectOutputStream(byteOut);
			        out.writeObject(src);
			        ByteArrayInputStream byteIn = new ByteArrayInputStream(byteOut.toByteArray());
			        ObjectInputStream in = new ObjectInputStream(byteIn);
			        try {
						dest = (List<T>) in.readObject();
					} catch (ClassNotFoundException e) {
						e.printStackTrace();
					}
				} catch (IOException e1) {
					e1.printStackTrace();
				}
		        
		    return dest;
		}
	/**
	 * 将字符数组转换为带单引号的字符串
	 * 
	 * @param arr
	 * @return
	 */
	public static String listToString(List list) {
		StringBuffer sb = new StringBuffer();
		if (list.size() <= 0) {
			sb.append("('')");
			return sb.toString();
		}
		if (null != list && list.size() > 0) {
			sb.append("(");
			for (int i = 0; i < list.size(); i++) {
				sb.append("'").append(list.get(i)).append("'").append(",");
			}
			sb.delete(sb.length() - 1, sb.length());
			sb.append(")");
		}
		return sb.toString();
	}
	
}
